/*
 * Bsp_Uart.c
 *
 *  Created on: Apr 4, 2025
 *      Author: Administrator
 */
#include"Bsp_Uart.h"



#define ENABLE_UART_DMA    1


RxBuffer uartBuffer;

uint8_t RxTemp = 0;

void USART1_Init(void){

	uartBuffer.head = uartBuffer.tail = 0;
	HAL_UART_Receive_IT(&huart1, (uint8_t *)&RxTemp, 1);

}


void USART1_Send_U8 (uint8_t ch){

	HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);

}


void USART1_Send_ArrayU8(uint8_t *BufferPtr, uint16_t Length){

	#if ENABLE_UART_DMA
	if(HAL_UART_GetState(&huart1) == HAL_UART_STATE_READY) {
	    HAL_UART_Transmit_DMA(&huart1, BufferPtr, Length);
	}
	#else
	while(Length--){
		USART1_Send_U8(*BufferPtr);
		BufferPtr++;
	}
	#endif	
}



void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  	/* Prevent unused argument(s) compilation warning */
  	UNUSED(huart);
 	  
	UART_Buffer_Put(RxTemp);
 	//继续接收数据
 	HAL_UART_Receive_IT(&huart1, (uint8_t *)&RxTemp, 1);
}

/*******************************************************/
int UART_Buffer_Put(uint8_t data) {
    if (UART_Buffer_IsFull()) {
        return -1; // 缓冲区已满
    }
    uartBuffer.buffer[uartBuffer.head] = data;
    uartBuffer.head = (uartBuffer.head + 1) % UART_BUFFER_SIZE;
    return 0;
}

int UART_Buffer_Get(uint8_t *data) {
    if (UART_Buffer_IsEmpty()) {
        return -1; // 缓冲区为空
    }
    *data = uartBuffer.buffer[uartBuffer.tail];
    uartBuffer.tail = (uartBuffer.tail + 1) % UART_BUFFER_SIZE;
    return 0;
}

int UART_Buffer_IsFull(void) {
    return (uartBuffer.head + 1) % UART_BUFFER_SIZE == uartBuffer.tail;
}

int UART_Buffer_IsEmpty(void) {
    return uartBuffer.head == uartBuffer.tail;
}

uint16_t UART_Buffer_Count(void) {
    return (uartBuffer.head - uartBuffer.tail + UART_BUFFER_SIZE) % UART_BUFFER_SIZE;
}

/********************************************************/




#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
PUTCHAR_PROTOTYPE
{
    /* Place your implementation of fputc here */
    /* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
    HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
    return ch;
}

